package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.errorprone.annotations.Var;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.WmTreadLoaclUtil.WmTreadLocal;
import com.heima.wemedia.mapper.WmMediaMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 根据条件进行查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //分页检查
        dto.checkParam();
        //获取当前登录人的信息
        WmUser user = WmTreadLocal.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wmNewsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //对状态的精确查询,因为状态有很多种,前端页面会传入
        if (dto.getStatus() != null) {
            wmNewsLambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //对于关键字的模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wmNewsLambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //对于所属频道的id的精确查询,查看属于什么频道
        if (dto.getChannelId() != null) {
            wmNewsLambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //对于开始时间和结束时间的查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            //根据开始时间和结束时间进行筛选数据
            wmNewsLambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        //查询当前登录用户的文章
        wmNewsLambdaQueryWrapper.eq(WmNews::getUserId, user.getApUserId());

        //发布时间倒序查询
        wmNewsLambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        page = page(page, wmNewsLambdaQueryWrapper);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 文章发布的接口,保存草稿,修改文章
     *
     * @param wmNewsDto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto wmNewsDto) {
        //0.参数的判断
        if (wmNewsDto == null || wmNewsDto.getContent() == null) {
            //这里是文章发布,所以实体类不能为空,文章的内容也不能为空,否则就返回无效参数
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.保存或者修改文章
        WmNews wmNews = new WmNews();
        //拷贝,把dto中的内容拷贝到文章的实体类中
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        //因为拷贝的数据是名称相同,类型也得相同,但是有些数据拷贝不上,所以,需要手动进行添加
        if (wmNewsDto.getImages() != null && wmNewsDto.getImages().size() > 0) {
            //这里证明他是有数据的
            String imageStr = StringUtils.join(wmNewsDto.getImages(), ",");
            wmNews.setImages(imageStr);
        }
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        //保存文章的方法
        saveOrUpdateNews(wmNews);

        //2.判断是否是草稿 如果是草稿,就直接结束当前的方法
        if (wmNewsDto.getStatus().equals(WmNews.Status.NORMAL)) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //3.不是草稿,保存文章内容图片与素材的关系
        //提取图片中的信息,需要从dto的ccontent中提取出,这是提取内容中的图片
        List<String> images = drawUrlImage(wmNewsDto.getContent());
        saveRekativeInfoForContent(images,wmNews.getId());
        //4.不是操作,保存文章的封面图片与素材的关系
        saveRelativeInfoForCover(wmNewsDto,wmNews,images);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 第一个功能室:如果当前封面类型是自动的话,则设置封面类型的数据
     * 匹配的规则是
     * 1.如果内容的图片大于等于1小于3 则是单图 type 1
     * 2.如果内容大于3 则是多图 type是3
     * 如果内容没有图片 则是无图 type 是0
     *
     * 第二个功能是保存封面图片和素材的关系
     * @param wmNewsDto
     * @param wmNews
     * @param Materimages
     */
    private void saveRelativeInfoForCover(WmNewsDto wmNewsDto, WmNews wmNews, List<String> Materimages) {
        List<String> images = wmNewsDto.getImages();
        //判断是否是自动,如果是则设置内容为图片的封面
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            //接下来判断是否是多图,单图,还是无图
            //多图
            if (Materimages.size()>=3){
                //设置wmnews的type是3
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images=Materimages.stream().limit(3).collect(Collectors.toList());
            }else if (Materimages.size()>=1&&Materimages.size()<3){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images=Materimages.stream().limit(1).collect(Collectors.toList());
            }else {
                //无图的情况
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            //修改文章
            if (images.size()>0&&images!=null){
                wmNews.setImages(StringUtils.join(images,","));
            }
            //更新wmnews数据库
            updateById(wmNews);
        }
      //保存封面图片和素材的关系
        if (images.size()>0&&images!=null){
           saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }

    }

    /**
     * 保存图片的关系
     * @param images
     * @param id
     */
    private void saveRekativeInfoForContent(List<String> images, Integer id) {
        saveRelativeInfo(images,id, WemediaConstants.CANCEL_COLLECT_MATERIAL);

    }

    /**
     * 保存图片的关系的方法
     * @param images
     * @param id
     * @param type
     */
    @Autowired
   private WmMediaMapper wmMediaMapper;

    private void saveRelativeInfo(List<String> images, Integer id, Short type) {
        if (images!=null&&!images.isEmpty()){
            //这里面只有url,需要通过url来进行查询出来id
            List<WmMaterial> wmMaterials = wmMediaMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images));
            //这里面根据url查出来了一个list集合,这是实体类的集合,现在需要根据实体类通过stream流进行获取他的id的值
            List<Integer> wmMaterialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //这里需要做判断,判断素材是否有效
            if (wmMaterials==null||wmMaterials.size()==0){
                //手动抛出异常
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAILED);
            }
            //判断images和查出的数据库中的条数是否一致,不一致的话,也需要抛出异常
            if (images.size()!=wmMaterialIds.size()){
                //手动抛出异常
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAILED);
            }

            //这个方法可以手动批量的添加数据,自己手写的方法
            wmNewsMaterialMapper.saveRelations(wmMaterialIds,id,type);
        }


    }

    /**
     * 提取dto中的images中image的路径
     *
     * @param content
     * @return
     */
    private List<String> drawUrlImage(String content) {
        ArrayList<String> drawUrlImages = new ArrayList<>();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                String value = (String) map.get("value");
                drawUrlImages.add(value);

            }
        }

        return drawUrlImages;
    }

    private void saveOrUpdateNews(WmNews wmNews) {
        //添加没有的属性
        wmNews.setUserId(WmTreadLocal.getUser().getApUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
        if (wmNews.getId() == null) {
            //保存操作
            save(wmNews);
        } else {
            //修改操作
            //首先需要删除关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);

        }
    }

    /**
     * 查看文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult details(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews news = getById(id);
        if (news==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        return ResponseResult.okResult(news);
    }

    /**
     * 文章删除方法
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //1.判断id是否为空
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章不可缺少id");
        }

        //2.判断文章是否上架
        WmNews news = getById(id);
        if (news.getEnable().equals(1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章上架中不可删除");
        }
        //3.文章是否存在
        if (news==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");

        }
        return ResponseResult.okResult(removeById(id));
    }

    /**
     * 文章上下架的操作
     *
     * @param wmNewsDto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto wmNewsDto) {
        //参数的校验
        if (wmNewsDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"参数不存在");
        }
        WmNews wmNews = getById(wmNewsDto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章id不存在");
        }
        if (wmNews.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态,不可上架");
        }

        if (wmNews.getEnable()==0){
            wmNews.setEnable((short)1);
            return ResponseResult.okResult(updateById(wmNews));
        }
        if (wmNews.getEnable()==1){
            wmNews.setEnable((short)0);
        }
        return ResponseResult.okResult(updateById(wmNews));
    }
}
